package com.crazymakercircle.config;

import com.crazymakercircle.Balance.ImLoadBalance;
import com.crazymakercircle.util.SpringContextUtil;
import com.crazymakercircle.zk.CuratorZKclient;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/*
 * 配置类，用于创建和配置应用程序所需的Bean
 */
@Configuration
public class ZkClientConfig implements ApplicationContextAware
{
    /*// 从配置文件中获取ZooKeeper连接字符串*/
    @Value("${zookeeper.connect.url}")
    private String zkConnect;
    // 从配置文件中获取ZooKeeper会话超时时间
    @Value("${zookeeper.connect.SessionTimeout}")
    private String zkSessionTimeout;


    /*    设置Spring上下文，以便在应用程序中使用
     * @param applicationContext Spring应用上下文
     * @throws BeansException 当设置过程中出现错误时抛出
     * @see BeanInitializationException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
    {

        SpringContextUtil.setContext(applicationContext);

    }

    /*
     * 创建并配置CuratorZKClient bean
     *
     * @return CuratorZKclient实例
     */
    @Bean(name = "curatorZKClient")
    public CuratorZKclient curatorZKClient()
    {

        return new CuratorZKclient(zkConnect,zkSessionTimeout);
    }

    /*
     * 创建并配置ImLoadBalance bean
     *
     * @param curatorZKClient CuratorZKclient实例，用于负载均衡
     * @return ImLoadBalance实例
     */
    @Bean(name = "imLoadBalance")
    public ImLoadBalance imLoadBalance(CuratorZKclient curatorZKClient)
    {

        return new ImLoadBalance( curatorZKClient);
    }


}